#!/bin/bash
# 镜像恢复后验证脚本
# 用于验证从镜像恢复的服务器是否配置正确

set -e

echo "🔍 开始验证服务器恢复状态..."
echo ""

ERRORS=0

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

check_pass() {
    echo -e "${GREEN}✅ $1${NC}"
}

check_fail() {
    echo -e "${RED}❌ $1${NC}"
    ERRORS=$((ERRORS + 1))
}

check_warn() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# 1. 检查项目目录
echo "📁 检查项目目录..."
if [ -d "/home/ubuntu/PhotoEnhanceAI-web" ]; then
    check_pass "项目目录存在"
else
    check_fail "项目目录不存在"
    exit 1
fi

cd /home/ubuntu/PhotoEnhanceAI-web

# 2. 检查 .env 文件
echo ""
echo "🔐 检查环境变量配置..."
if [ -f ".env" ]; then
    check_pass ".env 文件存在"
    
    # 检查关键环境变量
    if grep -q "COS_SECRET_ID" .env && grep -q "COS_SECRET_KEY" .env; then
        check_pass "COS环境变量已配置"
    else
        check_fail "COS环境变量未配置"
    fi
    
    if grep -q "COS_REGION" .env && grep -q "COS_BUCKET_NAME" .env; then
        check_pass "COS配置完整"
    else
        check_fail "COS配置不完整"
    fi
else
    check_fail ".env 文件不存在"
fi

# 3. 检查 systemd 服务
echo ""
echo "⚙️  检查systemd服务..."
if systemctl list-unit-files | grep -q "photoenhance-gateway"; then
    check_pass "photoenhance-gateway服务已注册"
    
    if systemctl is-enabled photoenhance-gateway > /dev/null 2>&1; then
        check_pass "服务已设置为开机自启"
    else
        check_warn "服务未设置为开机自启（运行: sudo systemctl enable photoenhance-gateway）"
    fi
    
    # 检查服务状态，允许激活中的状态
    SERVICE_STATUS=$(systemctl is-active photoenhance-gateway 2>/dev/null || echo "inactive")
    if [ "$SERVICE_STATUS" = "active" ] || [ "$SERVICE_STATUS" = "activating" ]; then
        check_pass "服务正在运行（状态: $SERVICE_STATUS）"
    else
        # 如果systemd服务未运行，但端口在监听，说明可能是手动启动的
        if netstat -tlnp 2>/dev/null | grep -q ":5000 "; then
            check_warn "systemd服务未运行，但端口5000正在监听（可能是手动启动）"
        else
            check_fail "服务未运行（运行: sudo systemctl start photoenhance-gateway）"
        fi
    fi
else
    check_fail "photoenhance-gateway服务未注册"
fi

# 4. 检查代码版本
echo ""
echo "📝 检查代码版本..."
if [ -d ".git" ]; then
    CURRENT_COMMIT=$(git rev-parse --short HEAD)
    check_pass "当前代码版本: $CURRENT_COMMIT"
    
    # 检查是否有未提交更改
    if [ -z "$(git status --porcelain)" ]; then
        check_pass "工作目录干净"
    else
        check_warn "工作目录有未提交更改"
        git status --short | head -5
    fi
else
    check_warn "未检测到Git仓库"
fi

# 5. 检查Python依赖
echo ""
echo "🐍 检查Python环境..."
if command -v python3 > /dev/null 2>&1; then
    check_pass "Python3已安装: $(python3 --version)"
    
    # 检查关键Python包
    cd 1-gateway/02-api-gateway
    if python3 -c "import flask; import qcloud_cos" 2>/dev/null; then
        check_pass "关键Python依赖已安装"
    else
        check_fail "关键Python依赖未安装（运行: pip install -r requirements.txt）"
    fi
    cd ../..
else
    check_fail "Python3未安装"
fi

# 6. 检查API网关服务
echo ""
echo "🌐 检查API网关服务..."
sleep 2  # 等待服务完全启动

# 检查健康接口
HEALTH_RESPONSE=$(curl -s http://127.0.0.1:5000/api/v1/health 2>&1)
if echo "$HEALTH_RESPONSE" | grep -q "healthy"; then
    check_pass "API网关健康检查通过"
else
    check_fail "API网关健康检查失败"
    echo "响应: $HEALTH_RESPONSE"
fi

# 检查预签名URL接口
PRESIGNED_RESPONSE=$(curl -s -X POST http://127.0.0.1:5000/api/v1/upload/presigned-url \
    -H "Content-Type: application/json" \
    -d '{"user_id":"test","file_type":"image/jpeg","file_size":1000000,"filename":"test.jpg"}' 2>&1)

if echo "$PRESIGNED_RESPONSE" | grep -q "success.*true"; then
    check_pass "预签名URL接口正常"
else
    check_fail "预签名URL接口异常"
    echo "响应: $PRESIGNED_RESPONSE"
fi

# 7. 检查前端编译产物
echo ""
echo "🎨 检查前端编译..."
if [ -d "5-frontend/01-web-app/dist" ]; then
    if [ -f "5-frontend/01-web-app/dist/index.html" ]; then
        check_pass "前端编译产物存在"
    else
        check_warn "前端编译产物不完整（运行: cd 5-frontend/01-web-app && npm run build）"
    fi
else
    check_warn "前端未编译（运行: cd 5-frontend/01-web-app && npm run build）"
fi

# 8. 检查端口监听
echo ""
echo "🔌 检查端口监听..."
if netstat -tlnp 2>/dev/null | grep -q ":5000 "; then
    check_pass "端口5000正在监听"
else
    check_fail "端口5000未监听"
fi

# 总结
echo ""
echo "=========================================="
if [ $ERRORS -eq 0 ]; then
    echo -e "${GREEN}✅ 验证通过！所有关键配置正常。${NC}"
    exit 0
else
    echo -e "${RED}❌ 发现 $ERRORS 个问题，请根据上述提示修复。${NC}"
    exit 1
fi

